package action;

import config.ApplicationConfig;
import net.sf.json.JSONObject;
import server.HistoryServer;
import server.RegisterServer;
import server.SettingServer;
import server.UserServer;
import util.Decode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.LinkedHashMap;

/**
 * User: tum0r
 * Package Name: ${PACKAGE_NAME}
 * Time: 2019-03-11 Monday 15:47:33
 */
public class RandomUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        LinkedHashMap<String, String> pageConfig = ApplicationConfig.readConfig("page.json");
        request.setCharacterEncoding(pageConfig.get("encode"));
        response.setCharacterEncoding(pageConfig.get("encode"));

        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("user");
        session.setAttribute("infoTitle", "用户生成");
        session.setAttribute("panelColor", "blue");

        UserServer userServer = new UserServer();
        userServer.open();
        try {
            int userType = userServer.checkUserType(user);
            if (userType == 1) {
                int count = Integer.parseInt(request.getParameter("count"));
                String prefix = request.getParameter("prefix");
                String suffix = request.getParameter("suffix");
                int length = Integer.parseInt(request.getParameter("length"));
                if (prefix != null && suffix != null) {
                    userServer.randomUser(count, prefix, suffix, length);
                    session.setAttribute("infoContent", "生成成功，初始密码为用户名");
                } else {
                    session.setAttribute("panelColor", "red");
                    session.setAttribute("infoContent", "生成失败，信息有误或不完整");
                }
            } else {
                session.setAttribute("panelColor", "red");
                session.setAttribute("infoContent", "生成失败，你没有权限生成用户");
            }
        } catch (Exception e) {
            session.setAttribute("panelColor", "red");
            session.setAttribute("infoContent", "生成失败，信息有误或不完整");
        }
        userServer.close();

        session.setAttribute("return", "mine");
        response.sendRedirect("information.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
